package cn.rtplay.esp32camcar;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import cn.rtplay.esp32camcar.databinding.FragmentGearManualBinding;
import cn.rtplay.esp32camcar.toolUtils.LogUtil;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class GearManualFragment extends Fragment {

    private FragmentGearManualBinding mViewBinding;
    private final String TAG = "GearManualFragment";
    private ESP32UDPService mESP32UDPService;
    private boolean mIsStop = false;
    private static final int GEAR_STATE_NEUTRAL = 0;
    private static final int GEAR_STATE_REVERSE = 6;
    private int mGearState = GEAR_STATE_NEUTRAL;

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            LogUtil.v(TAG, "onServiceConnected in");
            mESP32UDPService = ((ESP32UDPService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mESP32UDPService = null;
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        mViewBinding = FragmentGearManualBinding.inflate(inflater, container, false);
        mViewBinding.gearBar.setListener(level -> {
            mGearState = level;
            mESP32UDPService.setCarLight(CarLedStatus.LIGHT_REVERSE, mGearState == GEAR_STATE_REVERSE);
        });
        mViewBinding.speedButton.setOnTouchListener((view, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: //手指按下
                    if ((!mIsStop) && (mESP32UDPService.getChargingState() == ESP32UDPService.CHARGING_STATUS_NOT_CHARGING)) {
                        switch (mGearState) {
                            case GEAR_STATE_NEUTRAL:
                                mESP32UDPService.setDriverSpeed(0, ESP32UDPService.DRIVE_FORWARD);
                                break;
                            case 1:
                                mESP32UDPService.setDriverSpeed(20, ESP32UDPService.DRIVE_FORWARD);
                                break;
                            case 2:
                                mESP32UDPService.setDriverSpeed(40, ESP32UDPService.DRIVE_FORWARD);
                                break;
                            case 3:
                                mESP32UDPService.setDriverSpeed(60, ESP32UDPService.DRIVE_FORWARD);
                                break;
                            case 4:
                                mESP32UDPService.setDriverSpeed(80, ESP32UDPService.DRIVE_FORWARD);
                                break;
                            case 5:
                                mESP32UDPService.setDriverSpeed(100, ESP32UDPService.DRIVE_FORWARD);
                                break;
                            case GEAR_STATE_REVERSE:
                                mESP32UDPService.setDriverSpeed(70, ESP32UDPService.DRIVE_BACKWARDS);
                                break;
                        }
                    }
                    mViewBinding.speedButton.setBackgroundResource(R.drawable.manual_accelerator_down);
                    break;
                case MotionEvent.ACTION_MOVE: //手指移动（从手指按下到抬起 move多次执行）
                    break;
                case MotionEvent.ACTION_UP: //手指抬起
                    mViewBinding.speedButton.setBackgroundResource(R.drawable.manual_accelerator);
                    break;
            }
            view.performClick();
            return false;
        });
        mViewBinding.stopButton.setOnTouchListener((view, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: //手指按下
                    mIsStop = true;
                    mESP32UDPService.setDriverSpeed(0, ESP32UDPService.DRIVE_FORWARD);
                    mViewBinding.stopButton.setBackgroundResource(R.drawable.stop_down);
                    mESP32UDPService.setCarLight(CarLedStatus.LIGHT_STOP, true);
                    break;
                case MotionEvent.ACTION_MOVE: //手指移动（从手指按下到抬起 move多次执行）
                    break;
                case MotionEvent.ACTION_UP: //手指抬起
                    mIsStop = false;
                    mViewBinding.stopButton.setBackgroundResource(R.drawable.stop);
                    mESP32UDPService.setCarLight(CarLedStatus.LIGHT_STOP, false);
                    break;
            }
            view.performClick();
            return false;
        });

        Intent esp32ServiceIntent = new Intent(getActivity(), ESP32UDPService.class);
        if (getActivity() != null) {
            getActivity().bindService(esp32ServiceIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
        return mViewBinding.getRoot();
    }
}